import { Service } from 'egg';
import { Op } from 'sequelize';
// 角色增删改查
export default class RoleService extends Service {
  async getRoleList() {
    const { ctx } = this;
    const roleList = await ctx.model.Role.findAll({
      order: [[ 'sort', 'ASC' ]],
    });
    return roleList;
  }
  async getRoleListByUserId(userId) {
    const { ctx } = this;
    const roleList = await ctx.model.Role.findAll({
      where: {
        id: {
          [Op.in]: await ctx.model.RoleMenu.findAll({
            where: {
              userId,
            },
          }).then(res => {
            return res.map(item => {
              return item.roleId;
            });
          }),
        },
      },
      order: [[ 'sort', 'ASC' ]],
    });
    return roleList;
  }
  async addRole(role: any) {
    const { ctx } = this;
    const roleList = await ctx.model.Role.create(role);
    return roleList;
  }
  async updateRole(role: any) {
    const { ctx } = this;
    const roleList = await ctx.model.Role.update(role, {
      where: {
        id: role.id,
      },
    });
    return roleList;
  }
  async getRoleById(id) {
    const { ctx } = this;
    const roleList = await ctx.model.Role.findOne({
      where: {
        id,
      },
    });
    return roleList;
  }
  async getRoleByName(name) {
    const { ctx } = this;
    const roleList = await ctx.model.Role.findOne({
      where: {
        name,
      },
    });
    return roleList;
  }
  async getRoleByCode(code) {
    const { ctx } = this;
    const roleList = await ctx.model.Role.findOne({
      where: {
        code,
      },
    });
    return roleList;
  }
  async getRoleByUserId(userId) {
    const { ctx } = this;
    const roleList = await ctx.model.Role.findOne({
      where: {
        id: {
          [Op.in]: await ctx.model.UserRole.findAll({
            where: {
              userId,
            },
          }).then(res => {
            return res.map(item => {
              return item.roleId;
            });
          }),
        },
      },
      order: [[ 'sort', 'ASC' ]],
    });
    return roleList;
  }
  // 删除
  async deleteRole(role) {
    const { ctx } = this;
    const roleList = await ctx.model.Role.destroy({
      where: {
        id: role.id,
      },
    });
    return roleList;
  }
}

